package com.isyscore.os.core.config;

import cn.hutool.core.io.resource.ResourceUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.isyscore.os.core.logger.DatasourceHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.InputStreamResource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.sql.DataSource;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;

/**
 * @author felixu
 * @since 2021.11.24
 */
@Configuration
public class ClickhouseDatasourceInitializer {

    @Value("${spring.application.name}")
    private String application;

    @Bean
    public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
        DynamicRoutingDataSource dynamicDatasource = (DynamicRoutingDataSource) dataSource;
        DataSourceInitializer initializer = new DataSourceInitializer();
        String dsName = DatasourceHolder.getDs(application);
        DataSource ds = dynamicDatasource.getDataSource(dsName);
        initializer.setDataSource(ds);
        if (StringUtils.isNotBlank(dsName)){
            initializer.setDatabasePopulator(databasePopulator());
        }
        return initializer;
    }

    private DatabasePopulator databasePopulator() {
        String sql = ResourceUtil.readUtf8Str("clickhouse/operation_log.sql");
        String db = DatasourceHolder.getDb(application);
        sql = MessageFormat.format(sql, db, db);
        InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(sql.getBytes(StandardCharsets.UTF_8)));
        return new ResourceDatabasePopulator(resource);
    }
}
